package gongshw.bank.servlets;

import gongshw.bank.factory.DaoFactory;
import gongshw.bank.model.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		execute (request, response);
	}

	public void execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		String idString = req.getParameter("id");
		User user = DaoFactory.getUserDao().find("cid", idString);
		if (user!=null) {
			req.getSession(true).setAttribute("user", user);
			resp.sendRedirect("Balance");
		} else {
			resp.sendError(HttpServletResponse.SC_FORBIDDEN, "login failed");
		}
		
	}

}
